package com.dianwoba.universe.redis.serializer;

import java.nio.charset.Charset;

import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.util.Assert;

import com.fasterxml.jackson.core.type.TypeReference;

/**
 * Simple String to byte[] (and back) serializer. Converts Strings into bytes and vice-versa using the specified charset
 * (by default UTF-8).
 * <p>
 * Useful when the interaction with the Redis happens mainly through Strings.
 * <p>
 * Does not perform any null conversion since empty strings are valid keys/values.
 * 
 * @author Costin Leau
 */
public class StringRedisSerializer implements RedisSerializer<String> {

	private final Charset charset;

	public StringRedisSerializer() {
		this(Charset.forName("UTF8"));
	}

	public StringRedisSerializer(Charset charset) {
		Assert.notNull(charset);
		this.charset = charset;
	}

	public String deserialize(byte[] bytes) {
		return (bytes == null ? null : new String(bytes, charset));
	}
	
	@Override
	public <V> V deserialize(byte[] bytes, Class<V> clazz) throws SerializationException {
		throw new UnsupportedOperationException("method unsupported.");
	}

	public byte[] serialize(String string) {
		return (string == null ? null : string.getBytes(charset));
	}

	@Override
	public <V> V deserialize(byte[] bytes, TypeReference<?> valueTypeRef) throws SerializationException {
		throw new UnsupportedOperationException("method unsupported.");
	}
}
